///*
// * Copyright 2022 learn-netty4 Project
// *
// * The learn-netty4 Project licenses this file to you under the Apache License,
// * version 2.0 (the "License"); you may not use this file except in compliance
// * with the License. You may obtain a copy of the License at:
// *
// *   https://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// * License for the specific language governing permissions and limitations
// * under the License.
// */
//package com.jxw.cloudpen.web.websockethandler;
//
//import com.alibaba.fastjson.JSONObject;
//import io.netty.buffer.ByteBufUtil;
//import io.netty.channel.ChannelFuture;
//import io.netty.channel.ChannelFutureListener;
//import io.netty.channel.ChannelHandlerContext;
//import io.netty.channel.SimpleChannelInboundHandler;
//import io.netty.handler.codec.http.*;
//import io.netty.handler.codec.http.websocketx.*;
//import lombok.extern.slf4j.Slf4j;
//
//import java.io.IOException;
//
//import static io.netty.handler.codec.http.HttpMethod.GET;
//import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
//import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
//
///**
// * 同时处理消息和
// */
//@Slf4j
//public class TestSocketServerHandler extends SimpleChannelInboundHandler<Object> {
//
//    private static final String WEBSOCKET_PATH = "/websocket";
//
//    private WebSocketServerHandshaker handshaker;
//
//    @Override
//    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws IOException {
//        //根据消息类型，处理两种不同的消息
//        log.info("msg is {} ",JSONObject.toJSONString(msg));
//        if (msg instanceof FullHttpRequest) {
//            handleHttpRequest(ctx, (FullHttpRequest) msg);
//        } else if (msg instanceof WebSocketFrame) {
//            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
//        }
//    }
//
//    @Override
//    public void channelReadComplete(ChannelHandlerContext ctx) {
//        ctx.flush();
//    }
//
//    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws IOException {
//        // 处理异常
//        if (!req.decoderResult().isSuccess()) {
//            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST,
//                                                                   ctx.alloc().buffer(0)));
//            return;
//        }
//
//        // 只允许get请求
//        if (!GET.equals(req.method())) {
//            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN,
//                                                                   ctx.alloc().buffer(0)));
//            return;
//        }
//
//        // websocket握手
//        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
//                getWebSocketLocation(req), null, true, 50 * 1024 * 1024);
//        handshaker = wsFactory.newHandshaker(req);
//        if (handshaker == null) {
//            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
//        } else {
//            handshaker.handshake(ctx.channel(), req);
//        }
//    }
//
//    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
//
//        // 处理各种websocket的frame信息
//        if (frame instanceof CloseWebSocketFrame) {
//            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
//            return;
//        }
//        if (frame instanceof PingWebSocketFrame) {
//            ctx.write(new PongWebSocketFrame(frame.content().retain()));
//            return;
//        }
//        if (frame instanceof TextWebSocketFrame) {
//            // 直接返回
//            //此处理
//            ctx.write(frame.retain());
////            LocalSession session = new LocalSession(ctx.channel());
////            ctx.channel().attr(LocalSession.SESSION_KEY).set(session);
////            SessionManger.addLocalSession(session);
////
//////            ctx.pipeline().remove(ConnectionHandler.this);
////            ctx.pipeline().addLast("decoder", new CommonRpcDecoderHandler());
////            ctx.pipeline().addLast("encoder", new CommonRpcEncoderHandler());
////            //心跳
//////                p.addLast("heartBeat",new HeartBeatServerHandler());
//////            ctx.pipeline().addLast("loginRequest",new LoginRequestHandler());
////            ctx.pipeline().addLast(new BusinHandler());
////            StreamData result = new StreamData();
////            result.setClientId(session.getClientId());
////            result.setType(1);
////            ctx.channel().writeAndFlush(ByteObjUtil.objToBytes(result));
//
////            ctx.write(frame.retain());
//            return;
//        }
//        if (frame instanceof BinaryWebSocketFrame) {
//            // 直接返回
//            ctx.write(frame.retain());
//
//        }
//    }
//
//    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
//        // 生成错误页面
//        HttpResponseStatus responseStatus = res.status();
//        if (responseStatus.code() != 200) {
//            ByteBufUtil.writeUtf8(res.content(), responseStatus.toString());
//            HttpUtil.setContentLength(res, res.content().readableBytes());
//        }
//        // 发送response
//        boolean keepAlive = HttpUtil.isKeepAlive(req) && responseStatus.code() == 200;
//        HttpUtil.setKeepAlive(res, keepAlive);
//        ChannelFuture future = ctx.write(res);
//        if (!keepAlive) {
//            future.addListener(ChannelFutureListener.CLOSE);
//        }
//    }
//
//    @Override
//    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
//        // 异常处理
//        log.error("出现异常",cause);
//        ctx.close();
//    }
//
//    private static String getWebSocketLocation(FullHttpRequest req) {
//        String location =  req.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
//            return "ws://" + location;
//    }
//}
